/**
 * 云静表格
 */
layui.use(['jquery', 'yunj', 'element', 'elemProgress', 'button', 'tableToolbar', 'table', "validate"], function () {
    let win = window;
    let doc = document;
    let $ = layui.jquery;
    let element = layui.element;
    let elemProgress = layui.elemProgress;
    let button = layui.button;
    let tableToolbar = layui.tableToolbar;
    let table = layui.table;
    let validate = layui.validate;

    class YunjTable {

        constructor(obj) {
            this.version = '1.0.0';                 // 版本号

            this.id = obj.id;                         // 当前对象id

            this.raw_el = obj.elem;                   // 原始元素

            this.raw_args = obj.args;                 // 原始数据

            this.box_el = null;                       // 顶部父元素

            this.state_box_el = null;                 // 状态栏父元素

            this.filter_box_el = null;                // 筛选表单父元素

            this.table_box_el = null;                 // 表格父元素

            this.default_toolbar_box_el = null;       // 右上角工具栏父元素

            this.url = null;                          //请求地址

            this.state = null;                      //当前状态

            this.iframe_width = null;                 //当前页面iframe宽度，变化时更新

            this.filter_form_el = null;               //筛选表单

            this.filter_fields = {};                  // 筛选表单字段实例容器

            this.field_sort = {};                     // 表格字段排序

            this.table = null;                      //当前表格对象

            this.table_curr_td = null;              //当前表格操作格子，用于触发工具栏展开绑定事件无效

            this.table_item_count = 0;              //当前表格数据项数量

            this.table_items = [];                  //当前表格数据项

            this.elemProgress = null;              // 表格加载进度对象

            this.init();
        }

        init() {
            let that = this;
            if (!that.id || !that.raw_args || win.yunj.isEmptyObj(that.raw_args)) return false;
            // 初始化布局
            that.init_layout();
            // 初始化
            that.set_data_init();
            // 进度0
            that.elemProgress = elemProgress({elem: that.box_el});
            // 渲染
            that.render().then(res => {
                // 设置事件绑定
                that.set_event_bind();
                // 进度100%
                that.elemProgress.reset_progress(100);
            });
        }

        // 初始化布局
        init_layout() {
            let that = this;
            let layout = '<div class="layui-card-body yunj-table-state-box"></div>';
            if (that.raw_args.hasOwnProperty('filter')) layout += '<div class="layui-card-body yunj-table-filter-box" style="padding-bottom: 0"></div>';
            layout += `<div class="layui-card-body yunj-table-table-box" style="padding-top: 0"><table class="layui-table" id="yunj_table_${that.id}" lay-filter="yunj_table_${that.id}"></table></div>`;
            if (that.raw_args.hasOwnProperty('default_toolbar')) layout += '<div class="layui-card-body yunj-table-default-toolbar-box" style="display: none;"></div>';
            layout = `<div class="layui-card yunj-table-box" lay-filter="${that.id}">${layout}</div>`;
            that.raw_el.after(layout);
        }

        // 数据初始化
        set_data_init() {
            let that = this;
            let id = that.id;
            let raw_args = that.raw_args;
            // 元素
            let boxEl = $(`.yunj-table-box[lay-filter=${id}]`);
            that.box_el = boxEl;
            that.state_box_el = boxEl.find('.yunj-table-state-box');
            that.filter_box_el = boxEl.find('.yunj-table-filter-box');
            that.table_box_el = boxEl.find('.yunj-table-table-box');
            that.default_toolbar_box_el = boxEl.find('.yunj-table-default-toolbar-box');
            // url
            that.url = raw_args.hasOwnProperty('url') ? raw_args.url : yunj.url(false);
            // 内容区宽度
            that.iframe_width = $(doc).width();
        }

        // 渲染
        async render() {
            let that = this;
            that.render_state();
            await that.render_filter();
            await that.render_table();
            // 渲染完成事件触发
            $(doc).trigger(`yunj_table_${that.id}_render_done`);
            return 'done';
        }

        // 渲染状态栏
        render_state() {
            let that = this;
            that.set_state_layout();
            // 设置当前状态
            that.state = that.state_box_el.find('.layui-this').data('state') || null;
        }

        // 设置状态栏布局
        set_state_layout() {
            let that = this;
            if (that.state_box_el.find('li').length > 0) return false;
            let states = that.raw_args.state;
            let layout = '';
            for (let state in states) {
                layout += `<li data-state="${state}">${states[state]}(<span class="count">0</span>)</li>`;
            }
            layout = `<div class="layui-tab layui-tab-brief state-box" lay-filter="${that.id}_state"><ul class="layui-tab-title">${layout}</ul></div>`;
            that.state_box_el.html(layout);
            that.state_box_el.find('.layui-tab-title li:first').addClass('layui-this');
        }

        // 渲染筛选表单
        async render_filter() {
            let that = this;
            await that.set_filter_form();

            let filterBoxEl = that.filter_box_el.find('.filter-form');
            if (filterBoxEl.length <= 0) return 'done';
            filterBoxEl.removeClass('filter-form-this');

            let filterFormEl = that.filter_box_el.find(`.filter-form[lay-filter=${that.id}_${that.state}_${that.state}]`);
            if (filterFormEl.length <= 0) return 'done';
            filterFormEl.addClass('filter-form-this');
            that.filter_form_el = filterFormEl;

            // 设置筛选表单布局（字段label、按钮、展开/收起）
            that.set_filter_form_layout();
            return 'done';
        }

        // 设置筛选表单
        async set_filter_form() {
            let that = this;
            if (!yunj.isEmptyObj(that.filter_fields) || !that.raw_args.hasOwnProperty('filter')) return 'done';

            let filter = that.raw_args.filter;
            for (let state in filter) {
                if (!filter.hasOwnProperty(state)) continue;
                let fields = filter[state];
                let formHtml = `<form class="layui-row layui-form layui-form-pane yunj-form filter-form" lay-filter="${that.id}_${state}_${state}">`;
                that.filter_box_el.append(formHtml);
                await that.set_filter_form_fields(state, fields);
            }
            return 'done';
        }

        // 设置筛选表单字段
        async set_filter_form_fields(state, fields) {
            let that = this;
            for (let key in fields) {
                if (!fields.hasOwnProperty(key)) continue;
                let args = fields[key];
                await new Promise((resolve) => {
                    yunj.formField(args.type, {
                        formId: that.id + '_' + state,
                        tab: state,
                        key: key,
                        args: args,
                    }).then(field => {
                        field.render(
                            `.filter-form[lay-filter=${that.id}_${state}_${state}]`,
                            `<div class="layui-col-xs12 layui-col-sm6 layui-col-md3 filter-form-item-box">__layout__</div>`
                        ).then(res => {
                            that.filter_fields[field.id] = field;
                            resolve('done');
                        });
                    });
                });
            }
            let lastItemHtml = `<div class="layui-col-xs12 layui-col-sm6 layui-col-md3 filter-form-item-box"><div class="layui-form-item yunj-form-item"></div></div>`;
            that.filter_box_el.find(`.filter-form[lay-filter=${that.id}_${state}_${state}]`).append(lastItemHtml);
            return 'done';
        }

        // 设置筛选表单布局
        set_filter_form_layout() {
            let that = this;
            if (!that.filter_form_el) return false;
            let filter_form_el = that.filter_form_el;

            that.set_filter_form_field_label_layout();

            that.set_filter_form_button_layout();

            //判断筛选字段数量是否>2（包含按钮）
            if (filter_form_el.find(".filter-form-item-box").length <= 2) return false;

            //适配屏宽
            let otherFormItemEl = filter_form_el.find(".filter-form-item-box:not(:first,:last)");
            if (win.screen.width > 768) {
                //展开其他的filter-form-item-box
                otherFormItemEl.show('fast');
                //隐藏展开、收起按钮
                filter_form_el.removeClass('filter-form-stow').addClass('filter-form-unfold');
            } else {
                //隐藏其他的filter-form-item-box
                otherFormItemEl.hide('fast');
                //显示展开、收起按钮
                filter_form_el.removeClass('filter-form-stow').addClass('filter-form-unfold');
            }
        }

        // 设置筛选表单字段label布局
        set_filter_form_field_label_layout() {
            let that = this;
            let labelMaxWidth = 0;
            let formItemEl = that.filter_form_el.find('.yunj-form-item:not(.layui-form-textarea):not(.yunj-form-editor):not(.yunj-form-markdown)');
            formItemEl.each(function () {
                let currLabelWidth = $(this).find('.layui-form-label').outerWidth();
                if (currLabelWidth > labelMaxWidth) labelMaxWidth = currLabelWidth;
            });
            formItemEl.find('.layui-form-label').css('width', labelMaxWidth + 2 + 'px');
        }

        // 设置筛选表单按钮布局
        set_filter_form_button_layout() {
            let that = this;
            let formItemEl = that.filter_form_el.find('.yunj-form-item:last');
            if (formItemEl.html().length > 0) return true;
            let filterFormID = `${that.id}_${that.state}`;
            let boxFilter = `.filter-form[lay-filter=${filterFormID}_${that.state}] .yunj-form-item:last`;
            button.search(filterFormID).render(boxFilter);
            button.reset(filterFormID).render(boxFilter);
            formItemEl.append(`<button type="button" class="layui-btn layui-btn-sm layui-btn-primary layui-icon filter-form-layout-control"></button>`);
        }

        // 渲染表格
        async render_table() {
            let that = this;
            await that.set_state_count();
            await that.render_table_handle();
            return 'done';
        }

        // 设置状态数量
        set_state_count() {
            let that = this;
            if (!that.raw_args.hasOwnProperty('state')) return new Promise(resolve => {
                resolve('done')
            });

            return new Promise(resolve => {
                let request_data = {builder_id: that.id, builder_async_type: 'state_count'};
                yunj.request({
                    url: that.url,
                    data: request_data,
                    eventTitle: '状态数量查询',
                    loading: {enable: false},
                    successCallback: function (requestArgs, responseRes) {
                        let states = responseRes.data;
                        if (!yunj.isEmptyObj(states)) {
                            for (let state in states) {
                                if (!states.hasOwnProperty(state)) continue;
                                let stateEl = that.state_box_el.find(`.state-box li[data-state=${state}]`);
                                if (stateEl.length > 0) {
                                    stateEl.find('.count').html(states[state]);
                                }
                            }
                        }
                        resolve('done');
                    },
                });
            });
        }

        // 渲染表格处理
        async render_table_handle() {
            let that = this;
            let id = that.id;
            let raw_args = that.raw_args;
            let filter = that.request_filter();
            let args = {
                elem: '#' + that.layui_table_id(),
                url: that.url,
                method: 'post',
                where: {builder_id: id, builder_async_type: 'items', filter: filter, sort: that.request_sort()},
                contentType: 'application/json',
                parseData: function (res) {
                    let data = res.data;
                    let items = yunj.isObj(data) && data.hasOwnProperty('items') ? data.items : [];
                    items.map(item => {
                        item.is_export = false;
                        return item;
                    });
                    that.table_items = items;
                    return {
                        "code": res.errcode,
                        "msg": res.msg,
                        "count": that.table_item_count,
                        "data": that.table_items
                    };
                },
                loading: true,
                text: {none: '暂无相关数据'},
                autoSort: false,
                cols: [],
                done: function (res) {
                    table.resize(this.id);
                    // 渲染表格完成事件触发
                    $(doc).trigger(`yunj_table_${that.id}_render_table_done`);
                }
            };

            // page
            args.page = raw_args.hasOwnProperty("page") && yunj.isObj(raw_args.page) && raw_args.page.hasOwnProperty(that.state) ? raw_args.page[that.state] : true;
            if (args.page) {
                // limit
                args.limit = raw_args.hasOwnProperty("limit") && yunj.isObj(raw_args.limit) && raw_args.limit.hasOwnProperty(that.state) ? raw_args.limit[that.state] : 20;
                // limits
                args.limits = raw_args.hasOwnProperty("limits") && yunj.isObj(raw_args.limits) && raw_args.limits.hasOwnProperty(that.state) ? raw_args.limits[that.state] : [10, 20, 30, 40, 50, 60, 70, 80, 90];
            }

            if (yunj.isObj(that.field_sort) && !yunj.isEmptyObj(that.field_sort)) {
                let field = Object.keys(that.field_sort)[0];
                args.initSort = {field: field, type: that.field_sort[field]}
            }

            // 表格头部工具栏
            await that.set_table_toolbar_args(args);

            // 表格头部右侧工具栏
            that.set_table_default_toolbar_args(args);

            // 表头
            await that.set_table_cols_args(args);

            // 数据量
            await that.set_table_item_count(filter);

            console.log(args);

            that.table = table.render(args);

            return 'done';
        }

        // 设置表格头部工具栏参数
        async set_table_toolbar_args(args) {
            let that = this;
            let id = that.id;
            let state = that.state;
            let raw_args = that.raw_args;
            if (!raw_args.hasOwnProperty('toolbar') || !raw_args.toolbar.hasOwnProperty(state)) return args;
            await new Promise(resolve => {
                tableToolbar({
                    tableId: id,
                    state: state,
                    key: 'toolbar',
                    options: raw_args.toolbar[state]
                }).render().then(obj => {
                    args.toolbar = `#${obj.id}`;
                    resolve('done');
                });
            });
            return args;
        }

        // 设置表格头部右侧工具栏参数
        set_table_default_toolbar_args(args) {
            let that = this;
            let state = that.state;
            let raw_args = that.raw_args;

            if (!raw_args.hasOwnProperty('default_toolbar')) return args;
            let default_toolbar = raw_args.default_toolbar[state];
            let defaultToolbar = [];

            for (let i = 0, len = default_toolbar.length; i < len; i++) {
                if (default_toolbar[i] === 'filter' || default_toolbar[i] === 'print') {
                    defaultToolbar.push(default_toolbar[i]);
                } else if (default_toolbar[i] === 'export') {
                    defaultToolbar.push({title: '数据导出', layEvent: 'export', icon: 'layui-icon-export'});
                } else if (default_toolbar[i] === 'import' && raw_args.hasOwnProperty("import")) {
                    defaultToolbar.push({title: '数据导入', layEvent: 'import', icon: 'layui-icon-upload'});
                }
            }
            if (default_toolbar.indexOf("import") === -1 && raw_args.hasOwnProperty('import')) {
                defaultToolbar.push({title: '数据导入', layEvent: 'import', icon: 'layui-icon-upload'});
            }

            if (defaultToolbar.length > 0) {
                args.toolbar = args.hasOwnProperty('toolbar') ? args.toolbar : true;
                args.defaultToolbar = defaultToolbar;
            }
            return args;
        }

        // 设置表格表头参数
        async set_table_cols_args(args) {
            let that = this;
            let id = that.id;
            let state = that.state;
            let raw_args = that.raw_args;
            if (!raw_args.hasOwnProperty('cols') || !raw_args.cols.hasOwnProperty(state)) return args;
            let cols = [];
            let raw_cols = raw_args.cols[state];
            for (let k in raw_cols) {
                if (!raw_cols.hasOwnProperty(k)) continue;
                let raw_col = raw_cols[k];
                let col = yunj.objSupp(raw_col, {
                    field: '',
                    title: '',
                    type: 'normal',
                    align: 'left',
                    sort: false,
                    fixed: false,
                    hide: false,
                    templet: '',
                });
                // 处理hide
                switch (raw_col.hide) {
                    case 'yes':
                        col.hide = true;
                        break;
                    case 'mobile_hide':
                        col.hide = yunj.isMobile();
                        break;
                    default:
                        col.hide = false;
                }
                // 处理templet
                let raw_templet = raw_col['templet'];
                if (raw_templet.length > 0) {
                    let templetArgs = {
                        tableId: id,
                        state: state,
                        key: raw_col.field,
                        args: raw_col,
                    };
                    await new Promise(resolve => {
                        yunj.tableCol(raw_templet, templetArgs).then(colObj => {
                            colObj.render().then(res => {
                                col['templet'] = `#${colObj.id}`;
                                resolve(`${templetArgs.key} done`);
                            });
                        });
                    });
                }

                if (raw_templet === 'action') col.minWidth = 80;
                cols.push(col);
            }
            args.cols = [cols];
            return 'done';
        }

        // 设置当前条件下的表格数据量
        set_table_item_count(filter = null) {
            let that = this;
            filter = filter || that.request_filter();
            return new Promise(resolve => {
                yunj.request({
                    url: that.url,
                    data: {builder_id: that.id, builder_async_type: 'count', filter: filter},
                    eventTitle: '数量查询',
                    loading: {enable: false},
                    successCallback: function (requestArgs, responseRes) {
                        let count = responseRes.data.count;
                        that.table_item_count = yunj.isPositiveInteger(count) ? count : 0;
                        resolve('done');
                    },
                });
            });
        }

        /**
         * 重载表格数据
         * @param is_first_page [是否从第一页开始]
         */
        reload_table_handle(is_first_page = true) {
            let that = this;
            let args = {where: {id: that.id, type: 'items', filter: that.request_filter(), sort: that.request_sort()}};
            if (is_first_page) args.page = {curr: 1};
            that.table.reload(args);
        }

        // 设置事件绑定
        set_event_bind() {
            let that = this;
            let id = that.id;
            let layID = that.layui_table_id();
            // 文档页面宽度发生变化时触发
            $(doc).resize(function () {
                let currIframeWidth = $(doc).width();
                let lastIframeWidth = that.iframe_width;
                if (currIframeWidth !== lastIframeWidth) {
                    that.iframe_width = currIframeWidth;
                    that.set_filter_form_layout();
                }
            });
            // 当前展开格子
            $(doc).off('mousedown', `.yunj-table-table-box div[lay-id=${layID}] .layui-table-grid-down`).on('mousedown', `.yunj-table-table-box div[lay-id=${layID}] .layui-table-grid-down`, function () {
                that.table_curr_td = $(this).closest('td');
            });
            // 展开格子事件
            $(doc).off('click', `.layui-table-tips-main .layui-btn-container[yunj-id=${id}] [lay-event]`).on('click', `.layui-table-tips-main .layui-btn-container[yunj-id=${id}] [lay-event]`, function () {
                if (!that.table_curr_td) return;
                let el = $(this);
                let layEvent = el.attr('lay-event');
                let layerIdx = el.closest('.layui-table-tips').attr('times');
                layer.close(layerIdx);
                that.table_curr_td.find(`[lay-event=${layEvent}]`).first().click();
            });
            // 切换状态选项卡
            element.on(`tab(${id}_state)`, function (data) {
                let state = $(this).data('state');
                let lastState = that.state;
                if (state === lastState) return false;
                that.state_tab_change().then();
            });
            // 监听筛选表单事件
            if (that.raw_args.hasOwnProperty('filter')) {
                // 展开/收起
                that.filter_box_el.on('click', '.filter-form-layout-control', function () {
                    if (that.filter_form_el.hasClass('filter-form-unfold')) {
                        //转换为收起
                        that.filter_form_el.removeClass('filter-form-unfold').addClass('filter-form-stow');
                    } else {
                        //转换为展开
                        that.filter_form_el.removeClass('filter-form-stow').addClass('filter-form-unfold');
                    }
                    that.filter_form_el.find(".filter-form-item-box:not(:first,:last)").slideToggle("fast");
                });
                // 重置
                that.filter_box_el.on('click', '.yunj-btn-reset', function () {
                    $(doc).trigger(`yunj_form_${that.id}_${that.state}_clear`);
                });
                // 搜索
                that.filter_box_el.on('click', '.yunj-btn-search', function () {
                    that.render_table_handle().then();
                });
            }
            // 监听工具栏事件
            table.on(`toolbar(yunj_table_${id})`, function (obj) {
                let el = $(this);
                let args = el.data('args');
                switch (obj.event) {
                    case 'open_popup':
                        let popupUrl = yunj.urlPushParam(args.url, {
                            raw_table: that.id,
                        });
                        yunj.openPopup(popupUrl, args.title, true);
                        break;
                    case 'open_tab':
                        let tabUrl = yunj.urlPushParam(args.url, {
                            raw_table: that.id,
                        });
                        yunj.openTab(tabUrl, args.title, true);
                        break;
                    case 'async_event':
                        args.ids = table.checkStatus(obj.config.id).data.map(row => {
                            return row.id
                        });
                        that.async_event_request(args);
                        break;
                    case 'export':
                        yunj.tableExport(that);
                        break;
                    case 'import':
                        let importUrl = that.raw_args.import[that.state];
                        importUrl = yunj.urlPushParam(importUrl, {
                            raw_table: that.id,
                        });
                        yunj.openPopup(importUrl, '数据导入', true);
                        break;
                }
            });
            // 监听表格内操作列事件
            table.on(`tool(yunj_table_${id})`, function (obj) {
                let el = $(this);
                let args = el.data('args');
                let rowData = obj.data;
                switch (obj.event) {
                    case 'open_popup':
                        let popupUrl = yunj.urlPushParam(args.url, {
                            id: rowData.id,
                            raw_table: that.id,
                        });
                        yunj.openPopup(popupUrl, args.title, true);
                        break;
                    case 'open_tab':
                        let tabUrl = yunj.urlPushParam(args.url, {
                            id: rowData.id,
                            raw_table: that.id,
                        });
                        yunj.openTab(tabUrl, args.title, true);
                        break;
                    case 'async_event':
                        args.ids = [rowData.id];
                        that.async_event_request(args, that);
                        break;
                }
            });
            // 监听表头排序事件
            table.on(`sort(yunj_table_${id})`, function (obj) {
                that.field_sort = ['asc', 'desc'].indexOf(obj.type) === -1 ? {} : {[obj.field]: obj.type};
                that.reload_table_handle(false);
            });
        }

        // 切换状态选项卡
        async state_tab_change() {
            let that = this;
            that.render_state();
            await that.render_filter();
            await that.render_table_handle();
            return 'done';
        }

        // 表格异步事件请求
        async_event_request(param) {
            let that = this;
            param = yunj.objSupp(param, {title: '操作请求', confirm_text: null, event: '', url: '', ids: []});
            if (!yunj.isArray(param.ids) || yunj.isEmptyArray(param.ids)) {
                yunj.msg('请勾选要操作的数据列');
                return false;
            }
            let filter = {event: param.event, ids: param.ids};
            let request_data = {builder_id: that.id, builder_async_type: 'event', filter: filter};
            yunj.request({
                url: param.url ? param.url : that.url,
                data: request_data,
                eventTitle: param.title,
                confirmText: param.confirm_text,
                successCallback: function (requestArgs, responseRes) {
                    if (responseRes.errcode) {
                        yunj.alert(responseRes.msg, 'error');
                        return;
                    }
                    let responseData = responseRes.data;
                    if (yunj.isObj(responseData) && responseData.hasOwnProperty('reload') && !responseData.reload) {
                        that.async_event_request_done(requestArgs, responseRes);
                        return;
                    }
                    that.render_table().then();
                    that.async_event_request_done(requestArgs, responseRes);
                },
            });
        }

        // 异步事件请求完成
        async_event_request_done(request_args, response_res) {
            let that = this;
            let requestData = request_args.data.filter;
            let responseData = response_res.data;
            let event = requestData.event;
            $(doc).trigger(`yunj_table_${that.id}_event_done`, [event, requestData, responseData]);
            $(doc).trigger(`yunj_table_${that.id}_event_${event}_done`, [requestData, responseData]);
        }

        // 验证筛选数据
        verify_state_filter_data(state, data) {
            let that = this;
            if (!yunj.isObj(data) || yunj.isEmptyObj(data)) return true;
            let verifyRule = {};            // 验证规则
            let verifyData = {};            // 验证数据
            let verifyDataTitle = {};       // 验证数据title
            // 组合验证参数
            let fields = that.raw_args.filter[state];
            for (let k in fields) {
                if (!fields.hasOwnProperty(k) || !data.hasOwnProperty(k)) continue;
                let field = fields[k];
                if (field.verify.length <= 0) continue;
                verifyRule[k] = field.verify;
                verifyData[k] = data[k];
                verifyDataTitle[k] = field.title;
            }
            // 验证
            validate.create({
                rule: verifyRule,
                ignore_rule_exist: true
            });
            validate.checkTips(verifyData, verifyDataTitle);
            return true;
        }

        /**
         * 请求筛选的条件
         * @param args
         * @returns {any}
         */
        request_filter(args = {}) {
            let that = this;
            args = yunj.objSupp(args, {
                filter: true,        // 是否包含筛选表单的值
                ids: false,          // 是否包含当前选中ids
                convert: true,       // 是否转换为json字符串
                state: that.state,    // 指定状态下的筛选条件（默认当前状态）
            });
            let data = {state: args.state};
            if (args.ids) data.ids = table.checkStatus(that.layui_table_id()).data.map(row => {
                return row.id
            });
            if (args.filter && that.filter_form_el) {
                let filterValues = yunj.formData(`${that.id}_${args.state}`);
                that.verify_state_filter_data(args.state, filterValues);
                data = Object.assign({}, data, filterValues);
            }
            return args.convert ? JSON.stringify(data) : data;
        }

        /**
         * 请求条件sort
         * @returns {string}
         */
        request_sort() {
            let that = this;
            return JSON.stringify(that.field_sort);
        }

        // layui正式的表格id
        layui_table_id() {
            return `yunj_table_${this.id}`;
        }

    }

    $(doc).ready(function () {
        win.yunj.table = {};

        let tableEls = $('table[type=yunj]');
        if (yunj.isEmptyObj(YUNJ_TABLE) || tableEls.length <= 0) return false;
        tableEls.each(function () {
            let id = $(this).attr('id');
            if (!YUNJ_TABLE.hasOwnProperty(id)) return true;
            let args = YUNJ_TABLE[id];
            win.yunj.table[id] = new YunjTable({
                id: id,
                elem: $(this),
                args: args
            });
        });
    });

});
